package com.ruoyi.chat.ws;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionConnectEvent;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class WebSocketEventListener {

    Logger log = LoggerFactory.getLogger(WebSocketEventListener.class);
    @Autowired
    private SimpMessagingTemplate messagingTemplate;//发送消息的对象 stomp 里面不用session发信息
    List<String> users = new ArrayList<>();//在线用户
    ObjectMapper objectMapper = new ObjectMapper();
    @Autowired
    RabbitTemplate rabbitTemplate;


    @EventListener
    public void handleWebSocketConnectListener(SessionConnectEvent event) throws JsonProcessingException {
        //获取请求头里面的用户名

        String username = event.getUser().getName();
        //添加到集合
        users.add(username);
        System.out.println(event);
        log.info("用户登录：" + username);
        //创建异步任务广播在线用户

        MessageVo chatMessage = new MessageVo(objectMapper.writeValueAsString(users), MessageVo.MessageType.JOIN);
        rabbitTemplate.convertAndSend("stomp", "", objectMapper.writeValueAsString(chatMessage));
        //messagingTemplate.convertAndSend("/topic/public", chatMessage);//对 /topic/public发信息


    }


    @EventListener
    public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) throws JsonProcessingException, InterruptedException {
        //从会话中取用户信息，在集合中移除，并广播所有用户

        String username = event.getUser().getName();
        users.remove(username);
        MessageVo chatMessage = new MessageVo(objectMapper.writeValueAsString(users), MessageVo.MessageType.LEAVE);
        rabbitTemplate.convertAndSend("stomp", "", objectMapper.writeValueAsString(chatMessage));
        //messagingTemplate.convertAndSend("/topic/public", chatMessage);
    }

}